package com.szpx.controller.HZJController;

import com.github.pagehelper.PageInfo;
import com.szpx.entity.HZJ.Course;
import com.szpx.service.CourseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api/courses")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 获取课程列表（分页+条件查询）
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param params 查询参数 (如 name, status)
     * @return 分页结果
     */
    @GetMapping
    public ResponseEntity<PageInfo<Course>> getCourses(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam Map<String, Object> params) {
        PageInfo<Course> pageInfo = courseService.getCoursesByPage(pageNum, pageSize, params);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * 根据ID获取单个课程详情
     * @param id 课程ID
     * @return 课程实体
     */
    @GetMapping("/{id}")
    public ResponseEntity<Course> getCourseById(@PathVariable Long id) {
        Course course = courseService.getCourseById(id);
        if (course != null) {
            return ResponseEntity.ok(course);
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 新增课程
     * @param course 课程实体
     * @return 创建后的课程实体
     */
    @PostMapping
    public ResponseEntity<Course> createCourse(@RequestBody Course course) {
        boolean success = courseService.createCourse(course);
        if (success) {
            // 返回创建成功后的实体（包含ID）
            return ResponseEntity.ok(course);
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 更新课程
     * @param id 课程ID
     * @param course 课程实体
     * @return 更新后的课程实体
     */
    @PutMapping("/{id}")
    public ResponseEntity<Course> updateCourse(@PathVariable Long id, @RequestBody Course course) {
        course.setId(id); // 确保ID一致
        boolean success = courseService.updateCourse(course);
        if (success) {
            return ResponseEntity.ok(courseService.getCourseById(id));
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除课程
     * @param id 课程ID
     * @return 无返回内容
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCourse(@PathVariable Long id) {
        boolean success = courseService.deleteCourse(id);
        if (success) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }
}
